package b2.widget.room
{
	import b2.config.*;
	import b2.net.*;
	import b2.player.*;
	import b2.scene.*;
	import b2.scene.fight.*;
	import b2.util.*;
	import b2.widget.*;
	import b2.widget.tab.*;
	
	import com.greensock.*;
	import com.smartfoxserver.v2.SmartFox;
	import com.smartfoxserver.v2.core.SFSEvent;
	import com.smartfoxserver.v2.entities.*;
	import com.smartfoxserver.v2.entities.variables.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.text.*;
	import flash.utils.Timer;
	
	import org.flixel.*;
	
	public class MatchDialog extends Tab
	{
		private const RANK_COLOR:Array = ["#FF0000", "#A0A000", "#00A000", "#0000FF"];
		private const RANK_NAME:Array = ["st", "nd", "rd", ""];
		
		public var campIndex:int;
		public var matchIndex:int;
		private var returnButton:BasicButton;
		private var closeButton:BasicButton;
		//游戏房间
		private var roomIndex:int;
		//时钟
		private var timer:Timer;
		//当前进度提示
		private var countDownText:TextField;
		//时钟文字
		private var clockText:TextField;
		//当前排名
		private var ranking:int;
		private var rankingText:TextField;
		
		private var lastRoomInfo:String;
		private var lastUserInfo:String;

		public function MatchDialog(campIndex:int, matchIndex:int)
		{
			this.campIndex = campIndex;
			this.matchIndex = matchIndex;
//			var matchConfig:CampConfig = Config.campConfigs[campIndex];
			//透明背景
			var bgr:Sprite = new Sprite();
			var gfx:Graphics = bgr.graphics;
			gfx.beginFill(0x000000, 0.01);
			gfx.drawRect(0, 0, BFont.stageWidth, BFont.stageHeight);
			gfx.endFill();
			addChild(bgr);
			//背景图片
			var RoomBgr:Class = ResourceHelper.getInstance().getClassByName("RoomBgr");
			var roomBgr:Sprite = new RoomBgr();
			roomBgr.width = 660;
			roomBgr.x = (BFont.stageWidth - roomBgr.width) / 2;
			roomBgr.y = (BFont.stageHeight - roomBgr.height) / 2;
			addChild(roomBgr);
			//LOGO
			var logoSprite:Sprite = new CLogo();
			logoSprite.x = 115;
			logoSprite.y = 100;
			logoSprite.width = 600;
			logoSprite.scaleY = logoSprite.scaleX;
			logoSprite.filters = [new ColorMatrixFilter(BFont.blackWhiteFilter)];
			logoSprite.alpha = 0.5;
			addChild(logoSprite);
			var container:Sprite = new Sprite();
			container.y = 10;
			addChild(container);
			//线框
			var lineRec:Sprite = new Sprite();
			lineRec.graphics.lineStyle(2, 0x27AAE1);
			lineRec.graphics.drawRoundRect(195, 90, 413, 75, 15, 15);
			lineRec.graphics.drawRoundRect(193, 175, 416, 340, 20, 20);
//			lineRec.graphics.drawRoundRect(18, 325, 416, 124, 20, 20);
			lineRec.filters = [new DropShadowFilter(2, 44, 0x000000, 1, 2, 2, 1, 1, false)];
			lineRec.alpha = 0.8;
			container.addChild(lineRec);
			//线框色块
			var rrect:Sprite = new Sprite();
			rrect.graphics.beginFill(0x204B6B);
			rrect.graphics.drawRoundRect(195, 90, 413, 75, 15, 15);
			rrect.graphics.endFill();
			rrect.graphics.beginFill(0x27AAE1);
			rrect.graphics.drawRoundRect(195, 177, 413, 30, 15, 15);
//			rrect.graphics.drawRoundRect(20, 327, 413, 25, 15, 15);
			rrect.graphics.endFill();
			rrect.alpha = 0.8;
			container.addChild(rrect);
			//倒计时文字
			countDownText = new TextField();
			countDownText.selectable = false;
        	countDownText.autoSize = TextFieldAutoSize.LEFT;
			countDownText.defaultTextFormat = new TextFormat("微软雅黑", 14, 0xFFFF00);
			countDownText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			countDownText.x = 210;
			countDownText.y = 95;
			container.addChild(countDownText);
			//时钟文字
			clockText = new TextField();
			clockText.selectable = false;
        	clockText.autoSize = TextFieldAutoSize.CENTER;
			clockText.defaultTextFormat = new TextFormat("微软雅黑", 48, 0xFFFFFF, true);
			clockText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			clockText.x = 185;
			clockText.y = 95;
			container.addChild(clockText);
			//排名文字
			rankingText = new TextField();
			rankingText.selectable = false;
        	rankingText.autoSize = TextFieldAutoSize.LEFT;
			rankingText.defaultTextFormat = new TextFormat("微软雅黑", 14, 0xFFFF00);
			rankingText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			rankingText.x = 490;
			rankingText.y = 135;
			container.addChild(rankingText);
			//返回按钮
			var ReturnButton:Class = ResourceHelper.getInstance().getClassByName("ButtonBgr0");
			returnButton = new BasicButton(ReturnButton, "退出");
			returnButton.x = 625;
			returnButton.y = 500;
			addChild(returnButton);
			returnButton.addEventListener(MouseEvent.CLICK, onCloseButtonClick);
			//关闭按钮
			var CloseButton:Class = ResourceHelper.getInstance().getClassByName("CloseButton");
			closeButton = new BasicButton(CloseButton);
			closeButton.x = 675;
			closeButton.y = 50;
			addChild(closeButton);
			closeButton.addEventListener(MouseEvent.CLICK, onCloseButtonClick);
			disableExitButton(true);
			TweenLite.delayedCall(3, disableExitButton, [false]);
			super("", 1, 10, 1);
			//玩家排名标题
			var rankingTitleText:TextField = new TextField();
			rankingTitleText.selectable = false;
        	rankingTitleText.autoSize = TextFieldAutoSize.LEFT;
			rankingTitleText.defaultTextFormat = new TextFormat("微软雅黑", 12, 0xFFFF00);
			rankingTitleText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			rankingTitleText.text = "排名        玩家名字        积分        战力        奖励荣誉        奖励石油";
			rankingTitleText.x = 210;
			rankingTitleText.y = 180;
			container.addChild(rankingTitleText);
			//玩家排名
			setPagePos(container.x + 200, container.y +210);
			setPageSelectorPos(container.x + 348, container.y + 485);
			for (var i:int = 0; i < 50; i++)
			{
				var matchPlayerItem:MatchPlayerItem = new MatchPlayerItem();
				addItem(matchPlayerItem, matchPlayerItem.width, matchPlayerItem.height);
			}
			refresh();
			var sfs:SmartFox = SmartFoxHelper.getInstance().sfs; 
//			sfs.addEventListener(SFSEvent.USER_ENTER_ROOM, onUserEnterRoom);
//			sfs.addEventListener(SFSEvent.USER_EXIT_ROOM, onUserExitRoom);
			sfs.addEventListener(SFSEvent.USER_VARIABLES_UPDATE, onUserVariablesUpdate);
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			this.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
		}
		
		private function onAddedToStage(event:Event):void
		{
			timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER, onTick);
			timer.start();
		}

		private function onRemovedFromStage(event:Event):void
		{
			timer.stop();
			timer.removeEventListener(TimerEvent.TIMER, onTick);
			timer = null;
		}
		
		//响应用户变量更新
		private function onUserVariablesUpdate(evt:SFSEvent):void
		{
			var changedVars:Array = evt.params.changedVars;
			var playerName:String = evt.params.user.getVariable("playerName").getStringValue();
			var matchHonour:int = evt.params.user.getVariable("matchHonour") == null ? 0: evt.params.user.getVariable("matchHonour").getIntValue();
			DebugPane.getInstance().addInfo("onUserVariablesUpdate: user, " + playerName + "; matchHonour, " + matchHonour);
			//战场荣誉更新
			if (changedVars.indexOf("matchHonour") >= 0)
			{
				refresh();
			}
		}
		
		//响应用户离开
		private function onUserExitRoom(evt:SFSEvent):void
		{
			var user:User = evt.params.user;
			var room:Room = evt.params.room;
			DebugPane.getInstance().addInfo(user.name + " exit " + room.name); 
			refresh();
		}
		
		//响应用户进入
		private function onUserEnterRoom(evt:SFSEvent):void
		{
			var user:User = evt.params.user;
			var room:Room = evt.params.room;
			DebugPane.getInstance().addInfo(user.name + " enter " + room.name); 
			refresh();
		}
		
		//刷新所有人的位置
		public function refresh():void
		{
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			var userIds:Array = new Array();
			for (var i:int = 0; i < Math.min(SmartFoxHelper.getInstance().sfs.lastJoinedRoom.userCount, items.length); i++)
			{
				var user:User = SmartFoxHelper.getInstance().sfs.lastJoinedRoom.userList[i];
				userIds.push(user.id);
			}
			userIds.sort(sortOnMatchHonour);
			for (i = 0; i < userIds.length; i++)
			{
				user = SmartFoxHelper.getInstance().sfs.lastJoinedRoom.getUserById(userIds[i]);
				var playerId:int = user.getVariable("playerId").getIntValue();
				var playerName:String = user.getVariable("playerName").getStringValue();
				var fightPoint:int = user.getVariable("fightPoint").getIntValue();
				var matchHonour:int = user.getVariable("matchHonour") == null ? 0: user.getVariable("matchHonour").getIntValue();
				var matchPlayerItem:MatchPlayerItem = items[i];
				var color:String = i < 3 ? RANK_COLOR[i] : "";
				var rankname:String = i < 3 ? RANK_NAME[i] : "";
				if (me.id == playerId)
					color = RANK_COLOR[3];
				matchPlayerItem.rankingText.htmlText = "<font color='" + color + "'> " + (i + 1).toString() + rankname + "</font>";
				matchPlayerItem.playerNameText.htmlText = "<font color='" + color + "'> " + playerName + "</font>";
				matchPlayerItem.matchHonourText.htmlText = "<font color='" + color + "'> " + matchHonour.toString() + "</font>";
				matchPlayerItem.fightPointText.htmlText = "<font color='" + color + "'> " + fightPoint.toString() + "</font>";
			}
			for (i = userIds.length; i < items.length; i++)
			{
				matchPlayerItem = items[i];
				matchPlayerItem.clear();
			}
			//更新我的排名
			ranking = userIds.indexOf(SmartFoxHelper.getInstance().sfs.mySelf.id) + 1;
			rankingText.htmlText = "我的排名<font color='#00FF00'> " + ranking + "/" + userIds.length + " </font>";
			rankingText.x = 600 - rankingText.width;
		}
		
		//战场荣誉排序
		private function sortOnMatchHonour(a:int, b:int):int
		{
			var room:Room = SmartFoxHelper.getInstance().sfs.lastJoinedRoom; 
			var userA:User = room.getUserById(a);
			var userB:User = room.getUserById(b);
			var matchHonourA:int = userA.getVariable("matchHonour") == null ? 0: userA.getVariable("matchHonour").getIntValue();
			var matchHonourB:int = userB.getVariable("matchHonour") == null ? 0: userB.getVariable("matchHonour").getIntValue();
			var fightPointA:int = userA.getVariable("fightPoint").getIntValue();
			var fightPointB:int = userB.getVariable("fightPoint").getIntValue();
			if (matchHonourA < matchHonourB)
				return 1;
			else if (matchHonourA > matchHonourB)
				return -1;
			else if (fightPointA < fightPointB)
				return -1;
			else if (fightPointA > fightPointB)
				return 1;
			else if (userA.id < userB.id)
				return -1;
			else if (userA.id > userB.id)
				return 1;
			else
				return 0;
		}
		
		private function computeShufflePos(currentRound:int):int
		{
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			var matchConfig:MatchConfig = campConfig.matchConfigs[matchIndex];
			//按用户id排序
			var userIds:Array = new Array();	
			for (var i:int = 0; i < Math.min(SmartFoxHelper.getInstance().sfs.lastJoinedRoom.userCount, items.length); i++)
			{
				var user:User = SmartFoxHelper.getInstance().sfs.lastJoinedRoom.userList[i];
				userIds.push(user.id);
			}
			userIds.sort();
			var srand:Number = FlxU.srand(ServerHelper.getInstance().getClientDate() % 365 / 365 * (currentRound + 1) / matchConfig.round);
			//洗牌
			for (var times:int = 0; times < userIds.length; times++)
			{
				srand = FlxU.srand(srand);
				i = userIds.length * srand;
				srand = FlxU.srand(srand);
				var j:int = userIds.length * srand;
				var temp:int = userIds[i];
				userIds[i] = userIds[j];
				userIds[j] = temp;
			}
			return userIds.indexOf(SmartFoxHelper.getInstance().sfs.mySelf.id);
		}
		
		private function onTick(event:TimerEvent):void
		{
			var temp:String = "Entered rooms: ";
			for (var i:int = 0; i < SmartFoxHelper.getInstance().sfs.joinedRooms.length; i++)
			{
				var room:Room = SmartFoxHelper.getInstance().sfs.joinedRooms[i]; 
				temp += room.name + ", "; 
			}
			if (temp != lastUserInfo)
			{
				DebugPane.getInstance().addInfo(temp);
				lastUserInfo = temp;
			}
			temp = "Users: ";
			for (i = 0; i < SmartFoxHelper.getInstance().sfs.lastJoinedRoom.userCount; i++)
			{
				var user:User = SmartFoxHelper.getInstance().sfs.lastJoinedRoom.userList[i];
				var playerName:String = user.getVariable("playerName").getStringValue();
				temp += playerName + ", ";
			}
			if (temp != lastRoomInfo)
			{
				DebugPane.getInstance().addInfo(temp);
				lastRoomInfo = temp;
			}
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			//保持在签到房间中
			if (me.signUpMatchFlag && !me.inMatchFlag)
			{
				SmartFoxHelper.getInstance().enterMatchSignUpRoom(campIndex, matchIndex);
			}
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			var matchConfig:MatchConfig = campConfig.matchConfigs[matchIndex];
			var currentSeconds:int = int(ServerHelper.getInstance().currentSeconds()) % (24 * 60 * 60);
			var currentRound:int = Math.max(currentSeconds - (matchConfig.startTime + MatchConfig.signUpDuration) * 60, 0) / (matchConfig.roundDuration * 60);
			var remainSeconds:int;
			//还在轮次中
			if (currentRound < matchConfig.round)
			{
				//本轮战役索引
				var roundCampIndex:int = matchConfig.campIndex[currentRound];
				var roundCampConfig:CampConfig = Config.campConfigs[roundCampIndex];
				remainSeconds = currentSeconds - (matchConfig.startTime + MatchConfig.signUpDuration + 1) * 60 - currentRound * matchConfig.roundDuration * 60; 
				if (remainSeconds < 0)
				{
					countDownText.htmlText = "距第<font color='#00FF00'> " + (currentRound + 1).toString() + "/" + matchConfig.round + " </font>轮开始";
					remainSeconds = -remainSeconds;
					//提前10秒开始计算对阵表
					if (remainSeconds == 10)
					{
						this.roomIndex = computeShufflePos(currentRound) / (roundCampConfig.recommendedPlayer * 2);
					}
					//提前3秒开始进入游戏房间
					else if (remainSeconds > 0 && remainSeconds < 4)
					{
						SmartFoxHelper.getInstance().enterMatchRoom(campIndex, matchIndex, currentRound, this.roomIndex);
					}
				}
				else
				{
					countDownText.htmlText = "第<font color='#00FF00'> " + (currentRound + 1).toString() + "/" + matchConfig.round + " </font>轮进行中";
					//如果比赛已经进行，但房间还没有开始
					var roomDialog:RoomDialog = WidgetManager.getInstance().getWidget(RoomDialog) as RoomDialog;
					if (remainSeconds >= 8 && roomDialog != null)
					{
						me.matchHonour += 2;
						roomDialog.close();
						var popMessage:PopMessage = new PopMessage("本轮轮空，请等待下一轮开始！", 0xFF0000);
						WidgetManager.getInstance().popOut([popMessage], false, true);
						SmartFoxHelper.getInstance().enterMatchSignUpRoom(campIndex, matchIndex);
					}
				}
			}
			//轮次结束
			else
			{
				remainSeconds = currentSeconds - (matchConfig.startTime + MatchConfig.signUpDuration) * 60 - matchConfig.round * matchConfig.roundDuration * 60;
				if (remainSeconds < MatchConfig.endUpDuration)
				{
					countDownText.htmlText = "距比赛结束";
					remainSeconds = MatchConfig.endUpDuration - remainSeconds;
					//持续更新我的战场荣誉
					SmartFoxHelper.getInstance().updateMatchHonour(me.matchHonour);
				}
				else if (remainSeconds == MatchConfig.endUpDuration)
				{
					remainSeconds = MatchConfig.endUpDuration - remainSeconds;
					//比赛结束，保存比赛结果
					saveMatchResult();
				}
				else if (remainSeconds < MatchConfig.endUpDuration + MatchConfig.quitDuration)
				{
					countDownText.htmlText = "距自动退出";
					remainSeconds = MatchConfig.endUpDuration + MatchConfig.quitDuration - remainSeconds;
				}
				else
				{
					//退出比赛
					quitMatch();
				}
			}
			var minutes:int = remainSeconds / 60;
			var seconds:int = remainSeconds % 60;
			var timeStr:String = (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
			clockText.text = " " + timeStr + " ";
			clockText.x = 405 - clockText.width / 2;
		}
		
		//保存比赛结果
		private function saveMatchResult():void
		{
			//显示奖励
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			var matchConfig:MatchConfig = campConfig.matchConfigs[matchIndex];
			var room:Room = SmartFoxHelper.getInstance().sfs.lastJoinedRoom;
			for (var i:int = 0; i < Math.min(room.userCount, items.length); i++)
			{
				var matchPlayerItem:MatchPlayerItem = items[i];
				matchPlayerItem.honourAwardText.text = matchConfig.honourAward[Math.min(i, 10)];
				matchPlayerItem.oilAwardText.text = matchConfig.oilAward[Math.min(i, 10)];
			}
			for (i = room.userCount; i < items.length; i++)
			{
				matchPlayerItem = items[i];
				matchPlayerItem.clear();
			}
			//计算奖励
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			var honourAward:int = matchConfig.honourAward[ranking - 1];
			var oilAward:int = matchConfig.oilAward[ranking - 1];
			var objBalance:String = me.id + "," + CommonObjConfig.OIL + ",0,0,0," + oilAward + "," + 
				me.id + "," + CommonObjConfig.HONOUR + ",0,0,0," + honourAward + "," + 
				me.id + "," + CommonObjConfig.HONOUR_MEDAL + ",0,0,0," + honourAward;
			ServerHelper.getInstance().endFight(campIndex, 1, objBalance);
		}
		
		//退出比赛
		private function quitMatch():void
		{
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			me.signUpMatchFlag = false;
			me.inMatchFlag = false;
			me.matchHonour = 0; 
			SmartFoxHelper.getInstance().joinRoom(SmartFoxHelper.INITIAL_ROOM_NAME);
			close();
		}
		
		public function close():void
		{
			if (this.parent != null)
			{
				this.parent.removeChild(this);
			}
		}
		
		private function disableExitButton(flag:Boolean):void
		{
			returnButton.disable = flag;
			closeButton.disable = flag;
		}
		
		private function onCloseButtonClick(event:MouseEvent):void
		{
			if (!returnButton.disable)
			{
				quitMatch();
			}
		}
	}
}